// pages/profile/edit-profile.ts
import { MerchantAPI } from '../../utils/api'

interface EditProfileForm {
  nickName: string
  phonenumber: string
  email: string
  sex: string
  avatar: string
}

interface EditProfileData {
  statusBarHeight: number
  navHeight: number
  contentPaddingTop: number
  formData: EditProfileForm
  loading: boolean
  sexOptions: Array<{ value: string; label: string }>
  originalPhone: string
  phoneChanged: boolean
  phoneVerificationRequired: boolean
  smsCode: string
  smsCountdown: number
  smsSendEnabled: boolean
  requestingSms: boolean
}

Page({
  smsTimer: null as number | null,
  data: {
    statusBarHeight: 0,
    navHeight: 0,
    contentPaddingTop: 0,
    formData: {
      nickName: '',
      phonenumber: '',
      email: '',
      sex: '2',
      avatar: ''
    },
    loading: false,
    sexOptions: [
      { value: '0', label: '男' },
      { value: '1', label: '女' },
      { value: '2', label: '保密' }
    ],
    originalPhone: '',
    phoneChanged: false,
    phoneVerificationRequired: false,
    smsCode: '',
    smsCountdown: 0,
    smsSendEnabled: false,
    requestingSms: false
  } as EditProfileData,

  onLoad() {
    const systemInfo = wx.getSystemInfoSync()
    const statusBarHeight = systemInfo.statusBarHeight || 0
    const navHeight = statusBarHeight + 44
    this.setData({
      statusBarHeight,
      navHeight,
      contentPaddingTop: 0
    })
    this.loadPersonalInfo()
  },

  async loadPersonalInfo() {
    const cached = wx.getStorageSync('merchantPersonalInfo')
    if (cached) {
      this.setFormData(cached)
    }

    this.setData({ loading: true })
    try {
      const response = await MerchantAPI.getPersonalInfo()
      if (response.code === 200 && response.data) {
        this.setFormData(response.data)
        wx.setStorageSync('merchantPersonalInfo', response.data)
      }
    } catch (error) {
      console.error('加载个人信息失败:', error)
    } finally {
      this.setData({ loading: false })
    }
  },

  setFormData(data: any) {
    const phone = data.phonenumber || ''
    this.setData({
      formData: {
        nickName: data.nickName || '',
        phonenumber: phone,
        email: data.email || '',
        sex: data.sex != null ? String(data.sex) : '2',
        avatar: data.avatar || ''
      },
      originalPhone: phone,
      phoneChanged: false,
      phoneVerificationRequired: false,
      smsCode: '',
      smsCountdown: 0,
      smsSendEnabled: false
    })
    this.clearSmsCountdown()
  },

  onInputChange(e: any) {
    const field = e.currentTarget.dataset.field
    const value = e.detail.value || ''

    if (field === 'phonenumber') {
      const numeric = value.replace(/\D/g, '').slice(0, 11)
      const originalPhone = this.data.originalPhone
      const phoneChanged = numeric !== originalPhone
      const isValid = this.isValidPhone(numeric)

      this.setData({
        'formData.phonenumber': numeric,
        phoneChanged,
        phoneVerificationRequired: phoneChanged,
        smsSendEnabled: phoneChanged && isValid && this.data.smsCountdown === 0
      })

      if (!phoneChanged) {
        this.setData({
          phoneVerificationRequired: false,
          smsCode: '',
          smsSendEnabled: false
        })
        this.clearSmsCountdown()
      }
      return
    }

    this.setData({
      [`formData.${field}`]: value
    })
  },

  onSmsCodeInput(e: any) {
    const value = e.detail.value || ''
    this.setData({
      smsCode: value.replace(/\D/g, '').slice(0, 6)
    })
  },

  onSexChange(e: any) {
    const { value } = e.detail
    this.setData({
      'formData.sex': value
    })
  },

  chooseAvatar() {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: async (res) => {
        const tempFilePath = res.tempFilePaths[0]

        wx.showLoading({
          title: '上传中...',
          mask: true
        })

        try {
          const uploadRes = await MerchantAPI.uploadAvatar(tempFilePath)
          if (uploadRes.code === 200) {
            const avatarUrl =
              uploadRes.data?.avatar ||
              uploadRes.data?.avatarUrl ||
              uploadRes.avatar ||
              uploadRes.avatarUrl ||
              ''

            if (avatarUrl) {
              this.setData({ 'formData.avatar': avatarUrl })
            }

            wx.showToast({
              title: '头像更新成功',
              icon: 'success'
            })
          } else {
            wx.showToast({
              title: uploadRes.msg || '上传失败',
              icon: 'none'
            })
          }
        } catch (error) {
          console.error('上传头像失败:', error)
          wx.showToast({
            title: '上传失败',
            icon: 'none'
          })
        } finally {
          wx.hideLoading()
        }
      }
    })
  },

  async requestSmsCode() {
    if (this.data.requestingSms || !this.data.smsSendEnabled) {
      return
    }

    const phone = this.data.formData.phonenumber
    if (!this.isValidPhone(phone)) {
      wx.showToast({
        title: '请输入有效手机号',
        icon: 'none'
      })
      return
    }

    this.setData({ requestingSms: true })

    try {
      const res = await MerchantAPI.sendPersonalInfoSms(phone)

      if (res.code === 200) {
        wx.showToast({
          title: '验证码已发送',
          icon: 'success'
        })
        this.setData({
          smsCountdown: 60,
          smsSendEnabled: false,
          phoneVerificationRequired: true
        })
        this.startSmsCountdown()
      } else {
        wx.showToast({
          title: res.msg || '发送失败',
          icon: 'none'
        })
      }
    } catch (error) {
      console.error('发送验证码失败:', error)
      wx.showToast({
        title: '发送失败，请稍后重试',
        icon: 'none'
      })
    } finally {
      this.setData({ requestingSms: false })
    }
  },

  validateForm() {
    const { nickName, email, phonenumber } = this.data.formData
    const { phoneChanged, phoneVerificationRequired, smsCode } = this.data

    if (!nickName.trim()) {
      wx.showToast({
        title: '请输入昵称',
        icon: 'none'
      })
      return false
    }

    if (!this.isValidPhone(phonenumber)) {
      wx.showToast({
        title: '请输入有效手机号',
        icon: 'none'
      })
      return false
    }

    if (phoneChanged && phoneVerificationRequired) {
      if (!smsCode || smsCode.length !== 6) {
        wx.showToast({
          title: '请输入6位验证码',
          icon: 'none'
        })
        return false
      }
    }

    if (email && !/^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/.test(email)) {
      wx.showToast({
        title: '邮箱格式不正确',
        icon: 'none'
      })
      return false
    }

    return true
  },

  async saveProfile() {
    if (!this.validateForm()) {
      return
    }

    const { nickName, email, sex, avatar, phonenumber } = this.data.formData
    const { phoneChanged, smsCode } = this.data

    wx.showLoading({
      title: '保存中...',
      mask: true
    })

    try {
      const payload: any = {
        nickName: nickName.trim(),
        email: email.trim(),
        sex,
        avatar
      }

      if (phoneChanged) {
        payload.phonenumber = phonenumber
        payload.smsCode = smsCode
      }

      const response = await MerchantAPI.updatePersonalInfo(payload)

      if (response.code === 200) {
        wx.showToast({
          title: '保存成功',
          icon: 'success'
        })

        const cached = wx.getStorageSync('merchantPersonalInfo') || {}
        cached.nickName = nickName.trim()
        cached.email = email.trim()
        cached.sex = sex
        cached.phonenumber = phonenumber
        if (response.data && response.data.avatar) {
          cached.avatar = response.data.avatar
        } else if (avatar) {
          cached.avatar = avatar
        }
        wx.setStorageSync('merchantPersonalInfo', cached)

        setTimeout(() => {
          const pages = getCurrentPages()
          const prevPage = pages[pages.length - 2]
          if (prevPage && typeof prevPage.refreshMerchantInfo === 'function') {
            prevPage.refreshMerchantInfo()
          }
          wx.navigateBack({
            delta: 1
          })
        }, 1200)
      } else {
        wx.showToast({
          title: response.msg || '保存失败',
          icon: 'none'
        })
      }
    } catch (error) {
      console.error('保存个人信息失败:', error)
      wx.showToast({
        title: '保存失败，请稍后重试',
        icon: 'none'
      })
    } finally {
      wx.hideLoading()
    }
  },

  startSmsCountdown() {
    this.clearSmsCountdown()
    this.smsTimer = setInterval(() => {
      const current = this.data.smsCountdown
      if (current <= 1) {
        this.clearSmsCountdown()
        this.setData({
          smsCountdown: 0,
          smsSendEnabled: this.data.phoneChanged && this.isValidPhone(this.data.formData.phonenumber)
        })
      } else {
        this.setData({
          smsCountdown: current - 1
        })
      }
    }, 1000) as unknown as number
  },

  clearSmsCountdown() {
    if (this.smsTimer) {
      clearInterval(this.smsTimer)
      this.smsTimer = null
    }
  },

  isValidPhone(phone: string) {
    return /^1\d{10}$/.test(phone)
  },

  onUnload() {
    this.clearSmsCountdown()
  },

  goBack() {
    wx.navigateBack({
      delta: 1
    })
  }
})
